﻿using System.Windows.Documents;

using agsXMPP;

using VSTalk.Engine.Core.Context;
using VSTalk.Engine.Core.Feed;
using VSTalk.Model;

namespace VSTalk.Engine.ViewModel.Messenger.ThreadRenderer.BlockBuilder
{
    public class StatusBlockBuilder
    {
        private readonly Client _client;

        public StatusBlockBuilder(Client client)
        {
            _client = client;
        }

        public IModelContext ModelContext
        {
            get { return AppServices.Get<IModelContext>(); }
        }

        public Block CreateBlock(IMessage message)
        {
            var status = new Paragraph();
            status.Inlines.Add(CreateStatus(message));
            return status;
        }

        private Inline CreateStatus(IMessage message)
        {
            var from = message.XmppMessage.From;
            var name = GetName(from);
            var chatstate = message.XmppMessage.Chatstate.ToString();
            var span = new Span();
            span.Inlines.Add(string.Format("{0} is {1}...", name, chatstate));
            return new Italic(span);
        }

        private string GetName(Jid @from)
        {
            if (@from == null) return _client.Login;
            var client = ModelContext.GetClientByJid(from);
            if (client != null)
            {
                return client.Login;
            }
            var interlocutor = ModelContext.GetContactByJid(_client.Id, @from);
            if (interlocutor != null)
            {
                return interlocutor.Name;
            }
            var room = ModelContext.GetRoomByJid(_client.Id, @from);
            if (room != null)
            {
                return @from.Resource ?? room.Name;
            }
            return from;
        }
    }
}